import { util, InsideErr, BaseErr } from "utils";
import { getRequest } from "request";
import { API_GetCardInfo } from "../const/api";

function formatterData(res_data: any) {
    let { voiceResource, feeResource, flowResource } = res_data || {};
    // 语音
    let voice = {
        warn: voiceResource?.isWarn === "1",
        title: voiceResource?.dynamicVoiceTitle ?? "语音",
        value: voiceResource?.voicePersent ?? "",
        unit: voiceResource?.newUnit ?? "分钟",
    };
    // 话费
    let fee = {
        warn: feeResource?.isWarn === "1",
        title: feeResource?.dynamicFeeTitle ?? "话费",
        value: feeResource?.feePersent ?? "",
        unit: feeResource?.newUnit ?? "元",
    };
    // 流量
    let flow = {
        warn: flowResource?.isWarn === "1",
        title: flowResource?.dynamicFlowTitle ?? "流量",
        value: flowResource?.flowPersent ?? "",
        unit: flowResource?.newUnit ?? "GB",
    };
    return {
        voice,
        fee,
        flow,
    };
}

async function requestCardData(cookie: string): Promise<[err?: BaseErr, data?: any]> {
    // https://m.client.10010.com//mobileserviceimportant/home/queryUserInfoSeven?version=iphone_c@11.0503&desmobiel=16675552964&showType=0

    let [res_err, res_data] = await getRequest(API_GetCardInfo)(
        {
            version: "iphone_c@11.0503",
            desmobiel: "16675552964",
            showType: 0,
        },
        {
            contentType: "json",
            headers: {
                "X-Tingyun": "c=A|uBuVhVARE0A",
                "X-Tingyun-Id":
                    "4gA5HRiCw8g;c=2;r=42999170;u=35f5faa5023e7f9d301d45ecced1e536203f9afcaf074567cb6fd5ed3497599bc946e9c72683f42bdb6e202d0ede2780::BD4E4C616020FB61",
                Cookie: cookie,
            },
        }
    );

    if (!util.nilValue(res_err)) {
        return [res_err, null];
    }
    if (typeof res_data === "string" || typeof res_data === "number") {
        // 这也是错误...
        return [new BaseErr(-5008, `返回的是啥啊...${res_data}`), null];
    }
    // 判断标识符
    let { code } = res_data || {};
    if (code !== "Y") {
        return [new InsideErr(res_data), null];
    }

    // 正确返回
    return [undefined, formatterData(res_data)];
}

export { requestCardData };
